import { createRouter, createWebHistory } from "vue-router";
import HomeView from "../views/HomeView.vue";
import LayOut from "../views/layout/LayOut.vue";
import { $localStorage } from "@/utils/utils";

const routes = [
  {
    path: "/",
    redirect: "/layout/home",
  },
  {
    path: "/layout",
    name: "layout",
    component: LayOut,
    children: [
      {
        path: "home",
        name: "home",
        component: HomeView,
        meta: {
          title: "首页",
        },
      },
      {
        path: "about",
        name: "about",
        component: () => import("../views/AboutView.vue"),
        meta: {
          title: "关于我们",
        },
      },
      {
        path: "map3d",
        name: "map3d",
        component: () => import("@/views/map/index.vue"),
        meta: {
          title: "3D地图",
          parent: "地图",
        },
        children: [
          {
            path: "cesium",
            name: "cesium",
            component: () => import("@/views/map/child/child-one.vue"),
            meta: {
              title: "Cesium 页面",
              parent: "地图",
            },
          },
        ],
      },
      {
        path: "threejs",
        name: "threejs",
        component: () => import("@/views/threeJs/threejs-test.vue"),
        meta: {
          title: "Three.js 页面",
        },
      },
    ],
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login/Login.vue"),
  },
  {
    path: "/:pathMatch(.*)*",
    name: "notFound",
    component: () => import("../views/NotFoundView.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});

// 添加全局路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = !!$localStorage.getItem("token"); // 检查是否存在 token

  if (to.name !== "login" && !isAuthenticated) {
    next({ name: "login" });
  } else {
    next(); // 继续导航
  }
});

export default router;
